package com.dcits.ftz.auth;

import com.dcits.ftz.entity.User;
import com.dcits.ftz.service.IUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

/**
 * 全新实现的JWT Realm
 * 1. 支持JWT Token认证
 * 2. 实现基于数据库的RBAC授权
 */
@Component
public class JwtRealm extends AuthorizingRealm {

    private final JwtUtil jwtUtil;

    private final IUserService userService;

    public JwtRealm(JwtUtil jwtUtil, IUserService userService) {
        this.jwtUtil = jwtUtil;
        this.userService = userService;
    }

    /**
     * 必须重写此方法，否则Shiro会报错
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    /**
     * 授权逻辑 - 获取用户的角色和权限信息
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        // 1. 从PrincipalCollection中获取用户信息
        String username = jwtUtil.getUsernameFromToken(principals.toString());

        // 2. 通过用户名查询用户角色和权限（实际应从数据库获取）
        User user = userService.findByUserName(username);

        // 3. 创建授权信息对象
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();

        // 4. 设置角色和权限
        Set<String> roles = new HashSet<>();
        Set<String> permissions = new HashSet<>();

        // 模拟数据 - 实际应从数据库获取
        if ("admin".equals(username)) {
            roles.add("admin");
            roles.add("user");
            permissions.add("user:view");
            permissions.add("user:edit");
            permissions.add("user:delete");
        } else {
            roles.add("user");
            permissions.add("user:view");
        }

        authorizationInfo.setRoles(roles);
        authorizationInfo.setStringPermissions(permissions);

        return authorizationInfo;
    }

    /**
     * 认证逻辑 - 验证JWT Token的有效性
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
            throws AuthenticationException {

        // 1. 获取token
        String token = (String) authenticationToken.getCredentials();

        // 2. 从token中获取用户名
        String username = jwtUtil.getUsernameFromToken(token);
        if (username == null) {
            throw new AuthenticationException("无效的Token");
        }

        // 3. 查询用户是否存在（实际应查数据库）
        User user = userService.findByUserName(username);
        if (user == null) {
            throw new UnknownAccountException("用户不存在");
        }

        // 4. 验证token是否过期
        if (jwtUtil.isTokenExpired(token)) {
            throw new ExpiredCredentialsException("Token已过期，请重新登录");
        }

//         5. 验证用户状态是否正常
//        if (user.getStatus() != 1) {
//            throw new LockedAccountException("账号已被锁定，请联系管理员");
//        }

        // 6. 返回认证信息
        return new SimpleAuthenticationInfo(token, token, getName());
    }
}